package com.couldtest.consumerRibbonHystrix.controller;

import com.couldtest.consumerRibbonHystrix.MyCommand;
import com.couldtest.consumerRibbonHystrix.service.ConsumerService;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created by liguanfu on 2018/6/7.
 */
@RestController
public class DcController {
    @Autowired
    ConsumerService consumerService;

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/consumer")
    public String dc() {
        return consumerService.consumer();
    }


    @GetMapping("/consumer/async")
    public String async() throws ExecutionException, InterruptedException, TimeoutException {
        Future<String> stringFuture = consumerService.asyncOperate();
        Thread.sleep(2000L);
        String s = stringFuture.get(3000L, TimeUnit.MILLISECONDS);
        return "success";
    }

    @GetMapping("/update")
    public String update() {
        return consumerService.update();
    }


    @GetMapping("/consumer/hystrix")
    public String consumerHystrix(){
        //自定义hystrixCommand实现
        MyCommand myCommond = new MyCommand(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("")), restTemplate);
        //异步调用
        myCommond.queue();
        //同步调用
        myCommond.execute();
        return consumerService.update();
    }
}
